package cn.itcast.bos.web.action.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.CourierService;

@Namespace("/")
@ParentPackage("struts-default")
@Scope("prototype")
@Controller
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {
	private static final long serialVersionUID = 1L;
	@Autowired
	private CourierService courierService;

	private Courier courier = new Courier();

	@Override
	public Courier getModel() {
		return courier;
	}

	// 添加快递员
	@Action(value = "courier_add", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	public String add() {
		courierService.add(courier);
		return SUCCESS;
	}

	// 分页查询
	private Integer page;
	private Integer rows;

	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	@Action(value = "courier_pageQuery")
	public void pageQuery() throws IOException {
		// 构造分页查询的对象
		Pageable pageable = new PageRequest(page - 1, rows);
		// 构造条件查询的对象
		Specification<Courier> specification = new Specification<Courier>() {
			List<Predicate> list = new ArrayList<Predicate>();

			@Override
			// Root用于获取属性字段，CriteriaQuery可以用于简单条件查询，CriteriaBuilder 用于构造复杂条件查询
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				if (StringUtils.isNotBlank(courier.getCourierNum())) {
					Predicate p1 = cb.equal(root.get("courierNum").as(String.class), courier.getCourierNum());
					list.add(p1);
				}
				if (StringUtils.isNotBlank(courier.getCompany())) {
					Predicate p2 = cb.like(root.get("company").as(String.class), "%" + courier.getCompany() + "%");
					list.add(p2);
				}
				if (StringUtils.isNotBlank(courier.getType())) {
					Predicate p3 = cb.like(root.get("type").as(String.class), "%" + courier.getType() + "%");
					list.add(p3);
				}
				// root就相当于Courier,standardJoin就相当Standard
				// 多表查询
				Join<Courier, Standard> standardJoin = root.join("standard", JoinType.INNER);
				if (courier.getStandard() != null && StringUtils.isNotBlank(courier.getStandard().getName())) {
					Predicate p4 = cb.like(standardJoin.get("name").as(String.class),
							"%" + courier.getStandard().getName() + "%");
					list.add(p4);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};

		Page<Courier> pageData = courierService.findPageData(specification, pageable);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pageData.getTotalElements());
		map.put("rows", pageData.getContent());
		String jsonString = JSONArray.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}

	private String ids;

	public void setIds(String ids) {
		this.ids = ids;
	}

	// 作废
	@Action(value = "courier_del", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	public String del() {
		String[] idsArr = ids.split("-");
		courierService.del(idsArr);
		return SUCCESS;
	}

	// 恢复
	@Action(value = "courier_recover", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	public String recover() {
		String[] idsArr = ids.split("-");
		courierService.recover(idsArr);
		return SUCCESS;
	}

	// 查找所有没有关联定区的快递员
	@Action(value = "courier_findNoAssociation")
	public void findNoAssociation() throws IOException {
		List<Courier> list = courierService.findNoAssociation();
		String jsonString = JSONArray.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}

	// 查找所有快递员
	@Action(value = "courier_findAll")
	public void findAll() throws IOException {
		List<Courier> list = courierService.findAll();
		String jsonString = JSONArray.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
		ServletActionContext.getResponse().setContentType("application/json;charset=utf-8");
		ServletActionContext.getResponse().getWriter().write(jsonString);
	}
}
